package com.david.viewtest


import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Context
import android.content.res.Resources
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.View.OnClickListener
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import android.widget.TextView

class SpaceLineTabLayout(context: Context, attributeSet: AttributeSet) : HorizontalScrollView(context, attributeSet) {

    /**
     * 屏幕一半的值，提前计算避免后期每次都计算
     */
    private var halfWidth = resources.displayMetrics.widthPixels / 2

    /**
     * tab点击之后要滚动的距离，用于滚动动画计算
     */
    private var scrollDistance = 0

    /**
     * 上次滑动到的位置，用于滚动动画
     */
    private var lineScrollDistance = 0f

    /**
     * item左右内边距
     */
    private var itemHorizontalPadding = dp2px(14f).toInt()

    /**
     * 第一个item距离左边/做后一个item距离右边的外边距
     */
    private var startEndDistance = dp2px(10f).toInt()


    private val paint = Paint()

    /**
     * 动画对象
     */
    private val valueAnimator: ValueAnimator = ValueAnimator.ofFloat(0f, 1f)

    /**
     * 选中的位置，外部page变化之后初始化动画相关的变量
     */
    var selectIndex = 0
        set(value) {
            if (field == value) {
                return
            }

            field = value

            if (tabContainer.childCount == 0) {
                return
            }


            //计算相关数据：列表滑动起始点，横线滑动距离等
            targetView = tabContainer.getChildAt(value) as TextView
            val intArr = intArrayOf(0, 0)
            targetView?.getLocationOnScreen(intArr)
            val itemWidth = targetView?.width ?: 0

            lastScrollX = scrollX
            scrollDistance = intArr[0] - (halfWidth - itemWidth / 2)

            val endLeft = ((targetView?.left ?: 0) + itemWidth / 2).toFloat()
            lineScrollDistance = endLeft


            // TODO: 后期找到文字粗细渐变方法在迁移到动画处渐变， 目前文字样式先直接变化
            targetView?.typeface = Typeface.create("sans-serif", Typeface.BOLD)
            targetView?.setTextSize(TypedValue.COMPLEX_UNIT_PX, selectSize)
            targetView?.setTextColor(selectColor)
            lastSelectView?.typeface = Typeface.create("sans-serif", Typeface.NORMAL)
            lastSelectView?.setTextSize(TypedValue.COMPLEX_UNIT_PX, defaultSize)

            lastSelectView?.setTextColor(defaultColor)


            valueAnimator.start()
        }


    /**
     * tab的title列表
     */
    private val tabs: ArrayList<String> = ArrayList()

    /**
     * tab点击的回调
     */
    var tabSelectFunc: ((Int) -> Unit)? = null

    /**
     * tabView的容器
     */
    private val tabContainer = LinearLayout(context)

    /**
     * tab点击事件
     */
    private val tabClickListener: OnClickListener = OnClickListener { v ->
        // 可在此处添加快速点击判断，来触发双击事件

        v?.let {
            if (it.tag is Int) {
                val position = v.tag as Int
                if (position == selectIndex) {
                    return@OnClickListener
                }

                selectIndex = position

                tabSelectFunc?.invoke(position)
            }
        }
    }


    /**
     * 上次滚动到的位置，用于动画执行
     */
    private var lastScrollX = 0

    /**
     * 动画执行进度，0-1
     */
    private var animProgress = 0f

    /**
     * 上一次选中的tabView
     */
    private var lastSelectView: TextView? = null

    /**
     * 当前选中的tabView
     */
    private var targetView: TextView? = null


    /**
     * 动画执行相关的变量
     */
    private var selectColor = Color.parseColor("#242b29")
    private var defaultColor = Color.parseColor("#8E9496")

    //private val rColorDis = 0x8E - 0x24
    //private val gColorDis = 0x94 - 0x2b
    //private val bColorDis = 0x96 - 0x29
    private var selectSize = 20f
    private var defaultSize = 15f

    private var textGravity = Gravity.CENTER
    private var textBottomPadding = 0 //一般居底部显示时设置

    init {
        paint.color = Color.BLACK

        isHorizontalScrollBarEnabled = false

        addView(tabContainer, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, Gravity.CENTER_VERTICAL))

        valueAnimator.addUpdateListener {
            animProgress = it.animatedValue as Float

            //使用动画把选中的view滚动到屏幕中间
            scrollTo((lastScrollX + scrollDistance * animProgress).toInt(), 0)
            postInvalidate()
        }

        valueAnimator.addListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {}

            override fun onAnimationEnd(animation: Animator) {
                lastSelectView = targetView
            }

            override fun onAnimationCancel(animation: Animator) {}

            override fun onAnimationRepeat(animation: Animator) {}
        })


        val a = context.obtainStyledAttributes(attributeSet, R.styleable.CarInterTabLayout)
        defaultColor = a.getColor(R.styleable.CarInterTabLayout_TextDefaultColor, Color.parseColor("#8E9496"))
        defaultSize = a.getDimension(R.styleable.CarInterTabLayout_TextDefaultSize, 15f)
        selectColor = a.getColor(R.styleable.CarInterTabLayout_TextSelectColor, Color.parseColor("#242b29"))
        selectSize = a.getDimension(R.styleable.CarInterTabLayout_TextSelectSize, 20f)
        itemHorizontalPadding = a.getDimension(R.styleable.CarInterTabLayout_HorizontalPadding, dp2px(14f)).toInt()
        startEndDistance = a.getDimension(R.styleable.CarInterTabLayout_StartEndMargin, dp2px(10f)).toInt()
        textGravity = a.getInt(R.styleable.CarInterTabLayout_VerticalGravity, Gravity.CENTER)
        textBottomPadding = a.getDimension(R.styleable.CarInterTabLayout_BottomPadding, 0f).toInt()

        a.recycle()
    }

    fun setTabs(tempTabs: ArrayList<String>): SpaceLineTabLayout {
        tabs.clear()
        tempTabs.forEach {
            tabs.add(it)
        }

        post {
            setTabView()
        }
        return this
    }

    private fun setTabView() {
        if (tabs.isEmpty()) {
            return
        }
        tabContainer.removeAllViews()

        repeat(tabs.size) {
            val tab = TextView(context)

            tab.text = tabs[it]
            tab.tag = it
            tab.setOnClickListener(tabClickListener)

            //设置tab样式
            tab.gravity = textGravity
            if (textGravity == 81) { //Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL
                tab.setPadding(0, 0, 0, textBottomPadding)
            }

            tab.setTextColor(defaultColor)
            val typeface = Typeface.create("sans-serif", Typeface.NORMAL)
            tab.typeface = typeface

            tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, selectSize) //此处设置selectSize为计算选中后的宽度
            val params = LayoutParams((tab.paint.measureText(tabs[it]) + (itemHorizontalPadding shl 1)).toInt(), LayoutParams.MATCH_PARENT)

            tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, defaultSize)
            tab.layoutParams = params


            if (it == selectIndex) {
                lastSelectView = tab
                tab.setTextColor(selectColor)

                val typeface = Typeface.create("sans-serif", Typeface.BOLD)
                tab.typeface = typeface
                tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, selectSize)

                tab.includeFontPadding = false

                setStartUI(tab)
            }
            if (it == 0) {
                params.marginStart = startEndDistance
            } else if (it == tabs.size - 1) {
                params.marginEnd = startEndDistance
            }
            tabContainer.addView(tab)

            //if (it != tabs.size - 1) {
            //    val line = View(context)
            //    val layoutParams = LinearLayout.LayoutParams((0.5f).dp.toInt(), 12.dp)
            //    layoutParams.gravity = Gravity.CENTER_VERTICAL
            //    line.layoutParams = layoutParams
            //    line.setBackgroundColor(R.color.purchase_color_80ffffff.color())
            //    tabContainer.addView(line)
            //}
        }
    }

    private fun setStartUI(tab: View?) {
        if (tab == null) {
            return
        }
        //设置横线起始左偏移
        post {
            postInvalidate()

            if (selectIndex != 0) {
                val intArr = intArrayOf(0, 0)
                tab.getLocationOnScreen(intArr)
                scrollTo(intArr[0] - (halfWidth - tab.width / 2), 0)
            }
        }
    }

    override fun setVisibility(visibility: Int) {
        super.setVisibility(visibility)
        if (visibility == View.VISIBLE) {
            setStartUI(tabContainer.getChildAt(selectIndex))
        }
    }


    private fun dp2px(dp: Float): Float {
        val r = Resources.getSystem()
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.displayMetrics)
    }

    override fun onDraw(canvas: Canvas) {
        if (tabContainer.childCount > 0) {
            for (i in 0 until  tabContainer.childCount - 1) {
                canvas.drawLine(tabContainer.getChildAt(i).right.toFloat(), 0f , (tabContainer.getChildAt(i).right + 1).toFloat(), height.toFloat(), paint)
            }
        }
        super.onDraw(canvas)
    }

}